<!--
 * @Author: 陈俊升 761723995@qq.com
 * @Date: 2023-07-19 11:00:39
 * @LastEditors: 陈俊升 761723995@qq.com
 * @LastEditTime: 2023-12-23 18:12:06
 * @FilePath: /hr_new_vue3/src/views/Management/Contract/BaseSetting/ContractTemplate/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%A
-->
<!-- 合同-基础设置-合同类型及模板 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew :title="title" showBack></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20" class="box">
      <template #left>
        <a-input-search
          searchButton
          v-model="searchVal"
          @search="onSearch"
          @press-enter="onSearch"
          placeholder="请输入类型名称"
        ></a-input-search>
      </template>
      <template #right>
        <a-button type="primary" @click="addType(null)">新增合同类型</a-button>
        <a-button
          type="outline"
          @click="
            router.push({
              name: 'ContractTemplateGroup'
            })
          "
          >编辑分组</a-button
        >
      </template>
    </ConditionBox>
    <main id="main">
      <a-collapse :bordered="false" :default-active-key="defaultShowIds">
        <a-collapse-item v-for="item in groupList" :key="item.id" class="group">
          <template #header>
            <header>
              <span>{{ item.name }}</span>
            </header>
          </template>
          <template #extra>
            <a-button
              type="outline"
              @click.stop="del(null, item.id)"
              status="danger"
              >批量删除</a-button
            >
          </template>
          <a-table
            :data="item.children"
            v-model:selected-keys="selectedList"
            row-key="id"
            :row-selection="{
              type: 'checkbox',
              showCheckedAll: true,
              onlyCurrent: false
            }"
            @select="select"
            @select-all="(checked, group) => selectAll(checked, item)"
          >
            <template #columns>
              <a-table-column :width="80">
                <template #title> 序号 </template>
                <template #cell="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
              </a-table-column>
              <a-table-column :width="200" data-index="name" title="类型名称">
              </a-table-column>
              <a-table-column :width="200" data-index="remark" title="备注">
              </a-table-column>
              <a-table-column title="是否启用" data-index="enable" :width="150">
                <template #cell="{ record: { enable } }">
                  <a-tag
                    class="enable"
                    :color="
                      enable === 1
                        ? `rgb(var(--green-1))`
                        : 'rgb(var(--danger-1))'
                    "
                    :style="{
                      color:
                        enable === 1
                          ? `rgb(var(--green-6))`
                          : 'rgb(var(--danger-6))',
                      '--enable':
                        enable === 1
                          ? `rgb(var(--green-6))`
                          : 'rgb(var(--danger-6))'
                    }"
                  >
                    {{ enable === 1 ? '启用' : '停用' }}
                  </a-tag>
                </template>
              </a-table-column>
              <a-table-column
                :width="200"
                data-index=""
                title="操作"
                fixed="right"
                align="center"
              >
                <template #cell="{ record }">
                  <a-tooltip content="模板设置">
                    <IconFont
                      type="icon-setting-def"
                      :size="26"
                      :style="{
                        marginRight: '10px',
                        cursor: 'pointer'
                      }"
                      @click="goTemplate(record)"
                    />
                  </a-tooltip>
                  <a-tooltip content="编辑">
                    <IconFont
                      type="icon-edit"
                      :size="26"
                      :style="{
                        marginRight: '10px',
                        cursor: 'pointer'
                      }"
                      @click="addType(record)"
                    />
                  </a-tooltip>
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="del(record.id)"
                    >
                      <icon-font
                        type="icon-delete"
                        :size="26"
                        :style="{
                          cursor: 'pointer',
                          marginRight: '10px'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-collapse-item>
      </a-collapse>
      <a-back-top target-container="#main" :style="{ position: 'absolute' }" />
    </main>
  </ContentCard>
  <AddType
    v-model:visible="typeVisible"
    @typeEmit="typeEmit"
    :data="currTypeData"
  />
</template>

<script lang="ts" setup name="ContractTemplate">
import {
  GetContractGroup,
  PutContractGroupType,
  DelContractGroupType,
  AddContractGroupType
} from '@/apis/management/contract/baseSetting';
import AddType from './Components/AddType/index.vue';
import { Message, Modal } from '@arco-design/web-vue';

const router = useRouter();
const title = '合同类型及模板';
// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});
/* 储存选择的数据 */
const selectedList = ref([]);
let searchVal = ref(''); // 搜索框
let groupList = ref([]);
let defaultShowIds = ref([]); // 默认展开分组的id
const getData = async () => {
  try {
    const [groupListRes] = await Promise.all([
      GetContractGroup({
        name: searchVal.value,
        pageNumber: 0,
        pageSize: -1
      })
    ]);
    groupList.value = groupListRes.content;
    groupList.value.forEach((item: any) => {
      defaultShowIds.value.push(item.id);
    });
    currGroupId = groupListRes.content[0].id;
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

const onSearch = () => {
  getData();
};

let typeVisible = ref(false); // 新增合同类型弹出框
let currTypeData = ref({}); // 储存选中的合同类型数据

// 点击新增合同类型
const addType = (record: any | null) => {
  currTypeData.value = record;
  typeVisible.value = true;
};

// 新增类型自定义事件
const typeEmit = async (record: any) => {
  try {
    if (record) {
      // 如果是点击继续新增的话直接刷新列表数据
      if (typeof record === 'string') {
        getData();
      } else {
        if (record.id) await PutContractGroupType(record);
        else await AddContractGroupType(record);
        getData();
      }
    } else {
      currTypeData.value = record;
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

let currGroupId = 0;

// 全选按钮
const selectAll = (checked: boolean, group: any) => {
  console.log('====================================');
  console.log(group);
  console.log('====================================');
  nextTick(() => {
    if (selectedList.value.length === group.children.length) {
      return;
    }
    selectedList.value = group.children.map((row: any) => row.id);
  });
  currGroupId = group.id;
};

// 点击某一行按钮
const select = (
  rowKeys: string | number[],
  rowKey: string | number,
  record: any
) => {
  nextTick(() => {
    if (record.groupId !== currGroupId) {
      currGroupId = record.groupId;
      selectedList.value = [];
      selectedList.value.push(rowKey);
    } else {
      selectedList.value.push(rowKey);
    }
  });
};

const del = async (id: number | null, groupId?: number) => {
  try {
    console.log('========111============================');
    console.log(currGroupId, groupId);
    console.log('====================================');
    if (!id) {
      if (selectedList.value.length === 0 || currGroupId !== groupId) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              await DelContractGroupType({
                ids: selectedList.value
              });
              selectedList.value = [];
              getData();
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      await DelContractGroupType({
        ids: [id]
      });
      selectedList.value = [];
      getData();
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

let templateVisible = ref(false); // 新增合同模板弹出框

const goTemplate = ({ name, id }: { name: string; id: number }) => {
  router.push({
    name: 'ContractTemplateList',
    query: {
      typeId: id,
      name
    }
  });
};
</script>

<style scoped lang="less">
.box {
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999; /* 如果需要，可以设置一个较高的z-index值以确保它在其他元素之上 */
}
::v-deep .arco-table-th-title {
  font-weight: 600;
}
main {
  .group {
    header {
      font-size: 18px;
      font-weight: 700;
      height: 56px;
      line-height: 57px;
      // display: flex;
      // justify-content: space-between;
      span {
        &::before {
          content: '';
          display: inline-block;
          width: 6px;
          height: 50%;
          margin-right: 10px;
          background: #165dff;
          position: relative;
          top: 7px;
          border-radius: 3px;
        }
      }
    }
  }
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
:deep(.arco-collapse-item-content) {
  background-color: #fff;
}
</style>
